package top.jacktgq.itheima.netty.sticking_wrapping.wrapping.notResolve;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import top.jacktgq.utils.ByteBufUtil;

/**
 * @Author CandyWall
 * @Date 2021/3/23--16:49
 * @Description 粘包问题服务器
 */
@Slf4j
public class ShortConnectionServer {
    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);
        ChannelFuture channelFuture = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                // 调整系统的接收缓冲器（即滑动窗口）的大小
                // .option(ChannelOption.SO_RCVBUF, 10)
                // 调整Netty的接收缓冲区（ByteBuf）的大小，为复现半包问题做准备
                .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(16, 16, 16))
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                ByteBufUtil.log(byteBuf);
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                })
                .bind(8080);

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("服务器已启动...");
            }
        });
    }
}
